package com.sxpi.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class WxUtil {
    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取微信access_token
     */
    public static String getAccessToken(String appId, String appSecret) {
        try {
            String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                    appId, appSecret);

            log.info("Getting access_token with appId: {}", appId);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            log.info("Access token response: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                if (jsonObject.containsKey("access_token")) {
                    return jsonObject.getString("access_token");
                }
                if (jsonObject.containsKey("errcode")) {
                    // 如果是错误信息，抛出RuntimeException
                    throw new RuntimeException(String.format("获取access_token失败: errcode=%s, errmsg=%s",
                            jsonObject.getInteger("errcode"),
                            jsonObject.getString("errmsg")));
                }
                throw new RuntimeException("获取access_token失败: " + response.getBody());
            }
            throw new RuntimeException("获取access_token失败: " + response.getBody());
        } catch (Exception e) {
            log.error("获取access_token异常", e);
            throw new RuntimeException("获取access_token失败: " + e.getMessage());
        }
    }

    /**
     * 获取手机号
     */
    public static String getPhoneNumber(String accessToken, String code) {
        try {
            String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            JSONObject requestBody = new JSONObject();
            requestBody.put("code", code);

            HttpEntity<String> entity = new HttpEntity<>(requestBody.toJSONString(), headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                if (jsonObject.getIntValue("errcode") == 0) {
                    return jsonObject.getJSONObject("phone_info").getString("phoneNumber");
                }
                throw new RuntimeException("获取手机号失败: " + jsonObject.getString("errmsg"));
            }
            throw new RuntimeException("获取手机号失败: " + response.getBody());
        } catch (Exception e) {
            throw new RuntimeException("获取手机号失败: " + e.getMessage());
        }
    }

    /**
     * 获取openid
     */
    public static String getOpenId(String appId, String appSecret, String code) {
        try {
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    appId, appSecret, code);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                if (jsonObject.containsKey("openid")) {
                    return jsonObject.getString("openid");
                }
                throw new RuntimeException("获取openid失败: " + jsonObject.getString("errmsg"));
            }
            throw new RuntimeException("获取openid失败: " + response.getBody());
        } catch (Exception e) {
            throw new RuntimeException("获取openid失败: " + e.getMessage());
        }
    }
}
